/*
 * This class handles actual saving and retrieving data to persistent memory.
 * This class is managed by AgentManager to save Agents and called by one
 * of the Fragments in onPause() and similar methods.
 * 
 * Exceptions are thrown back to AgentManager where they should be handled
 */

package sk.stuba.fei.ut.snmpmanager;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

import android.content.Context;

public class AgentJSONSerializer
{
	private Context mContext;
	private String mFilename;

	public AgentJSONSerializer( Context c, String file )
	{
		// TODO: add verification for file ?
		mContext = c;
		mFilename = file;
	}

	/*
	 * Get List of Agents from Manager, for each Agent create its JSON form
	 * and write it to a private file storage
	 */
	public void saveAgents( ArrayList<Agent> agents ) throws JSONException,
			IOException
	{
		// build JSON array
		JSONArray array = new JSONArray();
		for ( Agent agent : agents )
			array.put( agent.toJSON() );

		Writer writer = null;
		try
		{
			OutputStream out = mContext.openFileOutput( mFilename,
					Context.MODE_PRIVATE );
			writer = new OutputStreamWriter( out );
			writer.write( array.toString() );
		}
		finally
		{
			if ( writer != null ) writer.close();
		}

	}

	public ArrayList<Agent> loadAgents() throws JSONException, IOException
	{
		ArrayList<Agent> agents = new ArrayList<Agent>();
		BufferedReader reader = null;
		try
		{
			// Open and read the file into a StringBuilder
			InputStream in = mContext.openFileInput( mFilename );
			reader = new BufferedReader( new InputStreamReader( in ) );
			StringBuilder jsonStringBuilder = new StringBuilder();
			String line = null;
			while ( ( line = reader.readLine() ) != null )
			{
				jsonStringBuilder.append( line );
			}

			// Parse the JSON using JSONTokener
			JSONArray array = ( JSONArray ) new JSONTokener(
					jsonStringBuilder.toString() ).nextValue();
			// build the array
			for ( int i = 0; i < array.length(); i++ )
			{
				agents.add( new Agent( array.getJSONObject( i ) ) );
			}
		}
		catch ( FileNotFoundException e )
		{
			// this happens when starting first time or file was deleted
			// so there is nothing to do anyway
		}
		finally
		{
			if ( reader != null ) reader.close();
		}

		return agents;
	}
}
